// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace SnapObjects.Data.AspNetCore
{
    internal class DataUnpackerFormater : IDataFormater
    {
        public bool CanFormat(Type modelType)
        {
            if (typeof(IDataUnpacker).IsAssignableFrom(modelType))
            {
                return true;
            }

            return false;
        }

        public async Task<object> FormatAsync(
            HttpRequest request, Type modelType, CancellationToken cancellationToken)
        {
            var dataFromat = DataReader.ReadDataFromatFromContentType(request.ContentType);

            if (dataFromat != null)
            {
                var data = await DataReader.ReadContentAsStringAsync(
                    request.Body, request.ContentType, cancellationToken);

                return new DataUnpacker(data, dataFromat.Value);
            }

            throw new NotSupportedException(
                String.Format(Properties.Resource.WEB_DATABINDING_EXCEPTION,
                request.ContentType,
                modelType.Name));
        }
    }
}
